﻿#!/usr/bin/env python
# coding=utf-8

from google.appengine.ext import db

import logging

class Person(db.Model):
  """用户类，key_name是用户名，password是密码，存在竞争关系"""
  password = db.StringProperty(required=True)
  
  @classmethod
  def is_exists(self, user_name):
    return Person.get_by_key_name(user_name) != None
    
  @classmethod
  def get_person_by_account(self,user_name):
    return Person.get_by_key_name(user_name)
  
  @classmethod
  def check_password(self, user_name, password):
    if not Person.is_exists(user_name):
      return False
    else:
      p = Person.get_by_key_name(user_name)
      return p.password == password
      
  @classmethod
  def change_password(self, user_name, old_password, new_password):
    """修改用户密码"""
    if not Person.is_exists(user_name):
      logging.error("用户不存在")
      return False
    
    if not Person.check_password(user_name, old_password):
      logging.error("输入的旧密码不正确")
      return False
      
    p = Person.get_person_by_account(user_name)
    p.password = new_password
    p.put()
    return True
    
  def save(self):
    """判断新建用户是否存在，如果不存在则把这个用户存入数据库"""
    p = Person.get_by_key_name(self.key().name())
    if p != None:
      return False
    self.put()
    return True
  
